package com.example.common.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证金额格式(2位小数)
 */
public class MoneyNumberValidator implements ConstraintValidator<MoneyNumber, String> {

    /**
     * 是否允许负号
     */
    boolean allowMinus = false;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (value == null) return true; // can be null

        if (allowMinus) {
            //(^-?[1-9](\d+)?(\.\d{1,2})?$)|(^-?0$)|(^-?\d\.\d{1,2}$)
            return value.matches("(^-?[1-9](\\d+)?(\\.\\d{1,2})?$)|(^-?0$)|(^-?\\d\\.\\d{1,2}$)");
        }

        //(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)
        return value.matches("(^[1-9](\\d+)?(\\.\\d{1,2})?$)|(^0$)|(^\\d\\.\\d{1,2}$)");
    }
}
